#!/usr/bin/python
"""
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
import getfeed
import notify
import cred
import indicate
import gobject
import gtk
import time
import os
import calendar
import textwrap
import pynotify
import webbrowser
import sys

#in seconds
TIME_GAP=60



def kaboom():
	global indicator
	def feednotify():
		feeds=getfeed.GetFeeds()
		notify.notify(feeds)

	feednotify()

	pwd = os.getcwd()
	dfile = os.path.join(pwd, "UbuGmailNotify.desktop")

	def timeout(indicators):
		feeds=getfeed.GetFeeds()
		for indicator in indicators:
			indicator.hide()
		shownew(feeds)
		return True

	def clicked(indicator):
		webbrowser.open_new_tab("""https://mail.google.com/""")
		indicator.hide()

	def server_display(server):
		pass

	server = indicate.indicate_server_ref_default()
	server.set_type("message.im")
	server.set_desktop_file(dfile)
	server.connect("server-display", server_display)
	server.show()


	def shownew(feeds):
		if (feeds['feed']['fullcount']=='0'):
			indicator=[]
		else:
			indicator=[]
			i=0
			for entry in feeds['entries']:
				print i
				indicator.append(indicate.Indicator())
				indicator[i].set_property("subtype", "im")
				indicator[i].set_property("sender",entry['title']+"\n\t"+entry['author']+"\n"+textwrap.fill(entry['summary'],50)+"\n")
				indicator[i].set_property_time("time",calendar.timegm(entry['published_parsed']))
				indicator[i].set_property('draw-attention', 'true')
				indicator[i].show()
				indicator[i].connect("user-display", clicked)
				i+=1
			pynotify.init("icon-summary-body")
			if (i==1):
				string="mail"
			else:
				string="mails"
			n=pynotify.Notification("Unread GMail","You have %d unread %s."%(i,string),"notification-message-IM")
			n.show()
		gobject.timeout_add_seconds(TIME_GAP,timeout,indicator)
		gtk.main()
	shownew(getfeed.GetFeeds())


if __name__ == "__main__":
	if(len(sys.argv) == 1):
		kaboom()
	else:
		if(sys.argv[1]=="delcred"):
			cred.GetCred(1)
		elif(sys.argv[1]=="help"):
			print """\nGmail Notifier for Ubuntu using the Indicator Applet.
When run without any arguments for the first time, UGN will ask for your
GMail Username and password and save it in the Gnome-keyring.\n\n
To delete the saved password and enter a new one provide delcred as a commandline parameter.\n\n"""
		else:
			print "Meaningless argument"
